import { useEffect, useRef, useState } from "react";
import Loading from "../Loading";
import style from "./style.module.less";
import type { LuYanImage } from "./types";

const Image: React.FC<{ img: LuYanImage; className?: string }> = (props) => {
  const imgRef = useRef<HTMLImageElement>(null);
  const imgContainerRef = useRef<HTMLImageElement>(null);

  const [loadead, setLoaded] = useState(false);

  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        (imgRef.current as HTMLImageElement).setAttribute("src", props.img.src);
        observer.unobserve(imgContainerRef.current as HTMLImageElement);
      }
    });
  });

  useEffect(() => {
    observer.observe(imgContainerRef.current as HTMLImageElement);
  });

  const handleLoaded = () => {
    setLoaded(true);
  };
  return (
    <div
      ref={imgContainerRef}
      className={`w-full h-full ${props.className} relative overflow-hidden`}
    >
      {!loadead && <Loading />}
      <img
        ref={imgRef}
        className={`w-full h-full absolute inset-0 object-cover animate__animated animate__fadeIn
         ${
           props.img.purity.toLowerCase() === "nsfw" ? style["iimage-nsfw"] : ""
         }
         ${
           props.img.purity.toLowerCase() === "sketchy"
             ? style["image-sketchy"]
             : ""
         }`}
        data-purity={props.img.purity}
        style={{ display: loadead ? "" : "none" }}
        referrerPolicy="no-referrer"
        onLoad={handleLoaded}
        src=""
      />
    </div>
  );
};

export default Image;
